package com.afollestad.materialdialogs;

import com.afollestad.materialdialogs.internal.MDButton;
import com.afollestad.materialdialogs.internal.MDRootLayout;
import com.afollestad.materialdialogs.internal.ThemeSingleton;
import com.afollestad.materialdialogs.utils.DialogUtils;
import com.afollestad.materialdialogs.utils.ResUtil;
import com.afollestad.materialdialogs.utils.UiUtil;
import ohos.agp.components.*;
import ohos.agp.components.element.Element;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.text.Font;
import ohos.agp.utils.Color;
import ohos.agp.window.dialog.CommonDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.global.icu.text.NumberFormat;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

/**
 * @author Aidan Follestad (afollestad)
 */
public class MaterialDialog extends DialogBase
        implements Component.ClickedListener, DefaultRvAdapter.InternalListCallback {
    private static final String TAG = MaterialDialog.class.getSimpleName();
    final Builder builder;
    private final EventHandler handler;
    Image icon;
    Text title, content, progressLabel, progressMinMax, inputMinMax;
    TextField input;
    ListContainer listContainer;
    Component titleFrame;
    StackLayout customViewFrame;
    ProgressBar progressBar;
    Checkbox checkBoxPrompt;
    DependentLayout buttonLayout;
    DirectionalLayout stackButtonLayout;
    MDButton positiveButton, stackPositiveButton, neutralButton, stackNegativeButton, negativeButton;
    ListType listType;
    List<Integer> selectedIndicesList;

    protected MaterialDialog(Builder builder) {
        super(builder.getContext());
        handler = new EventHandler(EventRunner.create());

        this.builder = builder;
        final LayoutScatter inflater = LayoutScatter.getInstance(builder.getContext());
        view = (MDRootLayout) inflater.parse(DialogInit.getInflateLayout(builder), null, false);
        setLayoutDimensions();
        DialogInit.init(this);
    }

    private void setLayoutDimensions() {
        view.setLayoutMeasureDimensions((width, height, lcHeight) -> {
            view.setLayoutConfig(new MDRootLayout.LayoutConfig(width, height));
            setSize(width, height);
        });
    }

    public final Builder getBuilder() {
        return builder;
    }

    public final void setTypeface(Text target, Font t) {
        if (t == null) {
            return;
        }
        target.setFont(t);
    }

    @SuppressWarnings("unused")
    public Object getTag() {
        return builder.tag;
    }

    final void checkIfListInitScroll() {
        if (listContainer == null) {
            return;
        }
        listContainer.getComponentTreeObserver().addTreeLayoutChangedListener(new ComponentTreeObserver.GlobalLayoutListener() {
            @Override
            public void onGlobalLayoutUpdated() {
                listContainer.getComponentTreeObserver().removeTreeLayoutChangedListener(this);
                if (listType == ListType.SINGLE || listType == ListType.MULTI) {
                    int selectedIndex;
                    if (listType == ListType.SINGLE) {
                        if (builder.selectedIndex < 0) {
                            return;
                        }
                        selectedIndex = builder.selectedIndex;
                    } else {
                        if (selectedIndicesList == null || selectedIndicesList.size() == 0) {
                            return;
                        }
                        Collections.sort(selectedIndicesList);
                        selectedIndex = selectedIndicesList.get(0);
                    }

                    final int fSelectedIndex = selectedIndex;
                    handler.postTask(new Runnable() {
                        @Override
                        public void run() {
                            listContainer.requestFocus();
                            listContainer.scrollTo(fSelectedIndex);
                        }
                    });
                }
            }
        });
    }

    /**
     * Sets the dialog RecyclerView's adapter/layout manager, and it's item click listener.
     */
    final void invalidateList() {
        if (listContainer == null) {
            return;
        } else if ((builder.items == null || builder.items.size() == 0) && builder.baseItemProvider == null) {
            return;
        }
        listContainer.setItemProvider(builder.baseItemProvider);
        if (listType != null) {
            ((DefaultRvAdapter) builder.baseItemProvider).setCallback(this);
        }
    }

    @Override
    public boolean onItemSelected(MaterialDialog dialog, Component view, int position, CharSequence text, boolean longPress) {
        if (!view.isEnabled()) {
            return false;
        }
        if (listType == null || listType == ListType.REGULAR) {
            // Default adapter, non choice mode
            if (builder.autoDismiss) {
                // If auto dismiss is enabled, dismiss the dialog when a list item is selected
                hide();
            }
            if (!longPress && builder.listCallback != null) {
                builder.listCallback.onSelection(this, view, position, builder.items.get(position));
            }
            if (longPress && builder.listLongCallback != null) {
                return builder.listLongCallback.onLongSelection(
                        this, view, position, builder.items.get(position));
            }
        } else {
            // Default adapter, choice mode
            if (listType == ListType.MULTI) {
                final Checkbox cb = (Checkbox) view.findComponentById(ResourceTable.Id_md_control);
                if (!cb.isEnabled()) {
                    return false;
                }
                final boolean shouldBeChecked = !selectedIndicesList.contains(position);
                if (shouldBeChecked) {
                    // Add the selection to the states first so the callback includes it (when alwaysCallMultiChoiceCallback)
                    selectedIndicesList.add(position);
                    if (builder.alwaysCallMultiChoiceCallback) {
                        // If the checkbox wasn't previously selected, and the callback returns true, add it to the states and check it
                        if (sendMultiChoiceCallback()) {
                            cb.setChecked(true);
                        } else {
                            // The callback cancelled selection, remove it from the states
                            selectedIndicesList.remove(Integer.valueOf(position));
                        }
                    } else {
                        // The callback was not used to check if selection is allowed, just select it
                        cb.setChecked(true);
                    }
                } else {
                    // Remove the selection from the states first so the callback does not include it (when alwaysCallMultiChoiceCallback)
                    selectedIndicesList.remove(Integer.valueOf(position));
                    if (builder.alwaysCallMultiChoiceCallback) {
                        // If the checkbox was previously selected, and the callback returns true, remove it from the states and uncheck it
                        if (sendMultiChoiceCallback()) {
                            cb.setChecked(false);
                        } else {
                            // The callback cancelled unselection, re-add it to the states
                            selectedIndicesList.add(position);
                        }
                    } else {
                        // The callback was not used to check if the unselection is allowed, just uncheck it
                        cb.setChecked(false);
                    }
                }
                builder.baseItemProvider.notifyDataSetItemChanged(position);
            } else if (listType == ListType.SINGLE) {
                final RadioButton radio = (RadioButton) view.findComponentById(ResourceTable.Id_md_control);
                if (!radio.isEnabled()) {
                    return false;
                }
                boolean allowSelection = true;
                final int oldSelected = builder.selectedIndex;

                if (builder.autoDismiss && builder.positiveText == null) {
                    // If auto dismiss is enabled, and no action button is visible to approve the selection, dismiss the dialog
                    hide();
                    // Don't allow the selection to be updated since the dialog is being dismissed anyways
                    allowSelection = false;
                    // Update selected index and send callback
                    builder.selectedIndex = position;
                    sendSingleChoiceCallback(view);
                } else if (builder.alwaysCallSingleChoiceCallback) {
                    // Temporarily set the new index so the callback uses the right one
                    builder.selectedIndex = position;
                    // Only allow the radio button to be checked if the callback returns true
                    allowSelection = sendSingleChoiceCallback(view);
                    // Restore the old selected index, so the state is updated below
                    builder.selectedIndex = oldSelected;
                }
                // Update the checked states
                if (allowSelection) {
                    builder.selectedIndex = position;
                    radio.setChecked(true);
                    builder.baseItemProvider.notifyDataSetItemChanged(oldSelected);
                    builder.baseItemProvider.notifyDataSetItemChanged(position);
                }
            }
        }
        return true;
    }

    final Element getListSelector() {
        if (builder.listSelector != 0) {
            return ResUtil.getPixelMapDrawable(builder.getContext(), builder.listSelector);
        }
        return getButtonSelector(0.0f);
    }

    public boolean isPromptCheckBoxChecked() {
        return checkBoxPrompt != null && checkBoxPrompt.isChecked();
    }

    private Element getButtonSelector(float radius) {
        UiUtil uiUtil = new UiUtil(builder.getContext());
        ShapeElement shapeElement = uiUtil.getShapeElement(ShapeElement.RECTANGLE, ResourceTable.Color_md_btn_selected, radius);
        return uiUtil.getStateElement(new int[]{ComponentState.COMPONENT_STATE_FOCUSED, ComponentState.COMPONENT_STATE_PRESSED}, shapeElement);
    }

    private Element getCustomButtonSelector(float radius) {
        UiUtil uiUtil = new UiUtil(builder.getContext());
        ShapeElement shapeElement = uiUtil.getShapeElement(ShapeElement.RECTANGLE, ResourceTable.Color_md_material_blue_800, radius);
        return uiUtil.getStateElement(new int[]{ComponentState.COMPONENT_STATE_PRESSED}, shapeElement);
    }

    Element getButtonSelector(DialogAction which, boolean isStacked) {
        if (isStacked) {

            if (builder.btnSelectorStacked != 0) {
                return ResUtil.getPixelMapDrawable(builder.getContext(), builder.btnSelectorStacked);
            }
            return getButtonSelector(0.0f);
        } else {
            switch (which) {
                default: {
                    if (builder.btnSelectorPositive
                            != 0) {
                        return getCustomButtonSelector(2.0f);
                    }
                    return getButtonSelector(2.0f);
                }
                case NEUTRAL: {
                    if (builder.btnSelectorNeutral != 0) {
                        return ResUtil.getPixelMapDrawable(builder.getContext(), builder.btnSelectorNeutral);
                    }
                    return getButtonSelector(2.0f);
                }
                case NEGATIVE: {
                    if (builder.btnSelectorNegative != 0) {
                        return ResUtil.getPixelMapDrawable(builder.getContext(), builder.btnSelectorNegative);
                    }
                    return getButtonSelector(2.0f);
                }
            }
        }
    }

    private boolean sendSingleChoiceCallback(Component v) {
        if (builder.listCallbackSingleChoice == null) {
            return false;
        }
        CharSequence text = null;
        if (builder.selectedIndex >= 0 && builder.selectedIndex < builder.items.size()) {
            text = builder.items.get(builder.selectedIndex);
        }
        return builder.listCallbackSingleChoice.onSelection(this, v, builder.selectedIndex, text);
    }

    private boolean sendMultiChoiceCallback() {
        if (builder.listCallbackMultiChoice == null) {
            return false;
        }
        Collections.sort(selectedIndicesList); // make sure the indices are in order
        List<CharSequence> selectedTitles = new ArrayList<>();
        for (Integer i : selectedIndicesList) {
            if (i < 0 || i > builder.items.size() - 1) {
                continue;
            }
            selectedTitles.add(builder.items.get(i));
        }
        return builder.listCallbackMultiChoice.onSelection(this,
                selectedIndicesList.toArray(new Integer[0]),
                selectedTitles.toArray(new CharSequence[0]));
    }

    @Override
    public final void onClick(Component v) {
        DialogAction tag = (DialogAction) v.getTag();
        switch (tag) {
            case POSITIVE: {
                if (builder.callback != null) {
                    builder.callback.onAny(this);
                    builder.callback.onPositive(this);
                }
                if (builder.onPositiveCallback != null) {
                    builder.onPositiveCallback.onClick(this, tag);
                }
                if (!builder.alwaysCallSingleChoiceCallback) {
                    sendSingleChoiceCallback(v);
                }
                if (!builder.alwaysCallMultiChoiceCallback) {
                    sendMultiChoiceCallback();
                }
                if (builder.inputCallback != null && input != null && !builder.alwaysCallInputCallback) {
                    builder.inputCallback.onInput(this, input.getText());
                }
                if (builder.autoDismiss) {
                    hide();
                }
                break;
            }
            case NEGATIVE: {
                if (builder.callback != null) {
                    builder.callback.onAny(this);
                    builder.callback.onNegative(this);
                }
                if (builder.onNegativeCallback != null) {
                    builder.onNegativeCallback.onClick(this, tag);
                }
                if (builder.autoDismiss) {
                    hide();
                }
                break;
            }
            case NEUTRAL: {
                if (builder.callback != null) {
                    builder.callback.onAny(this);
                    builder.callback.onNeutral(this);
                }
                if (builder.onNeutralCallback != null) {
                    builder.onNeutralCallback.onClick(this, tag);
                }
                if (builder.autoDismiss) {
                    hide();
                }
                break;
            }
        }
        if (builder.onAnyCallback != null) {
            builder.onAnyCallback.onClick(this, tag);
        }
    }

    @Override
    public void show() {
        try {
            super.show();
        } catch (Exception e) {
            try {
                throw new Exception(
                        "Bad window token, you cannot show a dialog " + "before an Screen is created or after it's hidden.");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }

    /**
     * Retrieves the view of an action button, allowing you to modify properties such as whether or
     * not it's enabled. Use {@link #//setActionButton(DialogAction, int)} to change text, since the
     * view returned here is not the view that displays text.
     *
     * @param which The action button of which to get the view for.
     * @return The view from the dialog's layout representing this action button.
     */
    public final MDButton getActionButton(DialogAction which) {
        switch (which) {
            default:
                return positiveButton;
            case NEUTRAL:
                return neutralButton;
            case NEGATIVE:
                return negativeButton;
        }
    }

    /**
     * Retrieves the view representing the dialog as a whole. Be careful with this.
     *
     * @return view
     */
    public final Component getView() {
        return view;
    }


    public final Text getInputEditText() {
        return input;
    }

    /**
     * Retrieves the custom view that was inflated or set to the MaterialDialog during building.
     *
     * @return The custom view that was passed into the Builder.
     */
    public final Component getCustomView() {
        return builder.customView;
    }

    @Override
    public CommonDialog setTitleText(String text) {
        title.setText(text);
        return super.setTitleText(text);
    }

    public final void setContent(CharSequence newContent) {
        content.setText(newContent.toString());
        content.setVisibility(newContent.toString().length() == 0 ? Component.HIDE : Component.VISIBLE);
    }

    public final void setContent(int newContentRes) {
        setContent(ResUtil.getString(builder.getContext(), newContentRes));
    }

    public final ArrayList<CharSequence> getItems() {
        return builder.items;
    }

    public final void notifyItemInserted(int index) {
        builder.baseItemProvider.notifyDataSetItemInserted(index);
    }

    public final void notifyItemsChanged() {
        builder.baseItemProvider.notifyDataChanged();
    }

    public final int getCurrentProgress() {
        if (progressBar == null) {
            return -1;
        }
        return progressBar.getProgress();
    }

    public final void incrementProgress(final int by) {
        setProgress(getCurrentProgress() + by);
    }

    private void setProgress(final int progress) {
        if (builder.progress <= -2) {
            return;
        }
        builder.context.getUITaskDispatcher().asyncDispatch(
                () -> {
                    progressBar.setProgressValue(progress);
                    if (progressLabel != null) {
                        progressLabel.setText(
                                builder.progressPercentFormat.format((float) getCurrentProgress() / (float) getMaxProgress()));
                    }
                    if (progressMinMax != null) {
                        progressMinMax.setText(
                                String.format(builder.progressNumberFormat, getCurrentProgress(), getMaxProgress()));
                    }
                }
        );
    }

    @SuppressWarnings("unused")
    public final boolean isIndeterminateProgress() {
        return builder.indeterminateProgress;
    }

    public final int getMaxProgress() {
        if (progressBar == null) {
            return -1;
        }
        return progressBar.getMax();
    }

    /**
     * Clears all selected checkboxes from multi choice list dialogs.
     *
     * @param sendCallback Defaults to true. True will notify the multi-choice callback, if any.
     */
    public void clearSelectedIndices(boolean sendCallback) {
        if (listType == null || listType != ListType.MULTI) {
            throw new IllegalStateException(
                    "You can only use clearSelectedIndices() " + "with multi choice list dialogs.");
        }
        if (builder.baseItemProvider != null && builder.baseItemProvider instanceof DefaultRvAdapter) {
            if (selectedIndicesList != null) {
                selectedIndicesList.clear();
            }
            builder.baseItemProvider.notifyDataChanged();
            if (sendCallback && builder.listCallbackMultiChoice != null) {
                sendMultiChoiceCallback();
            }
        } else {
            throw new IllegalStateException(
                    "You can only use clearSelectedIndices() " + "with the default adapter implementation.");
        }
    }

    @Override
    protected void onShow() {
        if (input != null) {
            DialogUtils.showKeyboard(this);
        }
        super.onShow();
    }

    void setInternalInputCallback() {
        if (input == null) {
            return;
        }
        input.addTextObserver((s, i, i1, i2) -> {
            final int length = s.length();
            boolean emptyDisabled = false;
            if (!builder.inputAllowEmpty) {
                emptyDisabled = length == 0;
                final Component positiveAb = getActionButton(DialogAction.POSITIVE);
                positiveAb.setEnabled(!emptyDisabled);
            }
            invalidateInputMinMaxIndicator(length, emptyDisabled);
            if (builder.alwaysCallInputCallback) {
                builder.inputCallback.onInput(MaterialDialog.this, s);
            }
        });
    }

    void invalidateInputMinMaxIndicator(int currentLength, boolean emptyDisabled) {
        if (inputMinMax != null) {
            if (builder.inputMaxLength > 0) {
                inputMinMax.setText(String.format(Locale.getDefault(), "%d/%d", currentLength, builder.inputMaxLength));
                inputMinMax.setVisibility(Component.VISIBLE);
            } else {
                inputMinMax.setVisibility(Component.HIDE);
            }
            final boolean isDisabled = (emptyDisabled && currentLength == 0) || (builder.inputMaxLength > 0
                    && currentLength > builder.inputMaxLength) || currentLength < builder.inputMinLength;
            final int colorText = isDisabled ? builder.inputRangeErrorColor : builder.contentColor;
            if (builder.inputMaxLength > 0) {
                inputMinMax.setTextColor(new Color(colorText));
            }
            final Component positiveAb = getActionButton(DialogAction.POSITIVE);
            positiveAb.setEnabled(!isDisabled);
        }
    }

    @Override
    public void hide() {
        if (input != null) {
            DialogUtils.hideKeyboard(this);
        }
        super.hide();
    }

    enum ListType {
        REGULAR,
        SINGLE,
        MULTI;

        public static int getLayoutForType(ListType type) {
            switch (type) {
                case REGULAR:
                    return ResourceTable.Layout_md_listitem;
                case SINGLE:
                    return ResourceTable.Layout_md_listitem_singlechoice;
                case MULTI:
                    return ResourceTable.Layout_md_listitem_multichoice;
                default:
                    throw new IllegalArgumentException("Not a valid list type");
            }
        }
    }

    /**
     * A callback used for regular list dialogs.
     */
    public interface ListCallback {

        void onSelection(MaterialDialog dialog, Component itemView, int position, CharSequence text);
    }

    /**
     * A callback used for regular list dialogs.
     */
    public interface ListLongCallback {

        boolean onLongSelection(MaterialDialog dialog, Component itemView, int position, CharSequence text);
    }

    /**
     * A callback used for multi choice (check box) list dialogs.
     */
    public interface ListCallbackSingleChoice {

        /**
         * Return true to allow the radio button to be checked, if the alwaysCallSingleChoice() option
         * is used.
         *
         * @param itemView
         * @param dialog   The dialog of which a list item was selected.
         * @param which    The index of the item that was selected.
         * @param text     The text of the item that was selected.
         * @return True to allow the radio button to be selected.
         */
        boolean onSelection(MaterialDialog dialog, Component itemView, int which, CharSequence text);
    }

    /**
     * A callback used for multi choice (check box) list dialogs.
     */
    public interface ListCallbackMultiChoice {

        /**
         * Return true to allow the check box to be checked, if the alwaysCallSingleChoice() option is
         * used.
         *
         * @param dialog The dialog of which a list item was selected.
         * @param which  The indices of the items that were selected.
         * @param text   The text of the items that were selected.
         * @return True to allow the checkbox to be selected.
         */
        boolean onSelection(MaterialDialog dialog, Integer[] which, CharSequence[] text);
    }

    /**
     * An alternate way to define a single callback.
     */
    public interface SingleButtonCallback {

        void onClick(MaterialDialog dialog, DialogAction which);
    }

    public interface InputCallback {

        void onInput(MaterialDialog dialog, CharSequence input);

    }

    public static class Builder {
        protected final Context context;
        CharSequence title, content, positiveText, neutralText, negativeText, inputPrefill, inputHint;
        GravityEnum titleGravity = GravityEnum.START, contentGravity = GravityEnum.START, btnStackedGravity = GravityEnum.END, itemsGravity = GravityEnum.START, buttonsGravity = GravityEnum.START;
        int buttonRippleColor, titleColor = -1, contentColor = -1, widgetColor, positiveColor, negativeColor, neutralColor, linkColor, selectedIndex = -1, maxIconSize = -1, dividerColor, backgroundColor, itemColor, progress = -2, progressMax = 0, inputType = -1, inputMinLength = -1, inputMaxLength = -1, inputRangeErrorColor = 0, listSelector, btnSelectorStacked, btnSelectorPositive, btnSelectorNeutral, btnSelectorNegative;
        ArrayList<CharSequence> items;
        boolean positiveFocus, neutralFocus, negativeFocus, alwaysCallMultiChoiceCallback = false, alwaysCallSingleChoiceCallback = false, canceledOnTouchOutside = true, autoDismiss = true, limitIconToDefaultSize, wrapCustomViewInScroll, indeterminateProgress, showMinMax, inputAllowEmpty, alwaysCallInputCallback, checkBoxPromptInitiallyChecked, indeterminateIsHorizontalProgress, titleColorSet = false, contentColorSet = false, itemColorSet = false, positiveColorSet = false, negativeColorSet = false, dividerColorSet = false;
        Component customView;
        ButtonCallback callback;
        SingleButtonCallback onPositiveCallback, onNegativeCallback, onNeutralCallback, onAnyCallback;
        ListCallback listCallback;
        ListLongCallback listLongCallback;
        ListCallbackMultiChoice listCallbackMultiChoice;
        ListCallbackSingleChoice listCallbackSingleChoice;
        Integer[] selectedIndices = null, disabledIndices = null;
        float contentLineSpacingMultiplier = 1.2f;
        Font regularFont, mediumFont;
        Element icon;
        BaseItemProvider baseItemProvider;
        OnShowListener showListener;
        OnDismissListener dismissListener;
        OnCancelListener cancelListener;
        StackingBehavior stackingBehavior;
        InputCallback inputCallback;
        int[] itemIds;
        CharSequence checkBoxPrompt;
        Checkbox.CheckedStateChangedListener checkBoxPromptListener;
        String progressNumberFormat;
        NumberFormat progressPercentFormat;
        Object tag;

        public Builder(Context context) {
            this.context = context;
            this.widgetColor = ResUtil.getColor(context, ResourceTable.Color_colorAccent);
            this.positiveColor = this.negativeColor = this.neutralColor = this.widgetColor;
            this.linkColor = ResUtil.getColor(context, ResourceTable.Color_md_link_color);
            this.buttonRippleColor = ResUtil.getColor(context, ResourceTable.Color_md_btn_ripple_color);
            this.progressPercentFormat = NumberFormat.getPercentInstance();
            this.progressNumberFormat = "%1d/%2d";

            checkSingleton();

            if (this.mediumFont == null) {
                try {
                    this.mediumFont = new Font.Builder("sans-serif-medium").build();
                } catch (Throwable ignored) {
                    this.mediumFont = Font.DEFAULT_BOLD;
                }
            }
            if (this.regularFont == null) {
                try {
                    this.mediumFont = new Font.Builder("sans-serif").build();
                } catch (Throwable ignored) {
                    this.regularFont = Font.SANS_SERIF;
                    if (this.regularFont == null) {
                        this.regularFont = Font.DEFAULT;
                    }
                }
            }
        }

        public final Context getContext() {
            return context;
        }

        public final int getItemColor() {
            return itemColor;
        }

        public final Font getRegularFont() {
            return regularFont;
        }

        private void checkSingleton() {
            if (ThemeSingleton.get(false) == null) {
                return;
            }
            ThemeSingleton s = ThemeSingleton.get();

            if (s.titleColor != 0) {
                this.titleColor = s.titleColor;
            }
            if (s.contentColor != 0) {
                this.contentColor = s.contentColor;
            }
            if (s.positiveColor != 0) {
                this.positiveColor = s.positiveColor;
            }
            if (s.neutralColor != 0) {
                this.neutralColor = s.neutralColor;
            }
            if (s.negativeColor != 0) {
                this.negativeColor = s.negativeColor;
            }
            if (s.itemColor != 0) {
                this.itemColor = s.itemColor;
            }
            if (s.icon != null) {
                this.icon = s.icon;
            }
            if (s.backgroundColor != 0) {
                this.backgroundColor = s.backgroundColor;
            }
            if (s.dividerColor != 0) {
                this.dividerColor = s.dividerColor;
            }
            if (s.btnSelectorStacked != 0) {
                this.btnSelectorStacked = s.btnSelectorStacked;
            }
            if (s.listSelector != 0) {
                this.listSelector = s.listSelector;
            }
            if (s.btnSelectorPositive != 0) {
                this.btnSelectorPositive = s.btnSelectorPositive;
            }
            if (s.btnSelectorNeutral != 0) {
                this.btnSelectorNeutral = s.btnSelectorNeutral;
            }
            if (s.btnSelectorNegative != 0) {
                this.btnSelectorNegative = s.btnSelectorNegative;
            }
            if (s.widgetColor != 0) {
                this.widgetColor = s.widgetColor;
            }
            if (s.linkColor != 0) {
                this.linkColor = s.linkColor;
            }
            this.titleGravity = s.titleGravity;
            this.contentGravity = s.contentGravity;
            this.btnStackedGravity = s.btnStackedGravity;
            this.itemsGravity = s.itemsGravity;
            this.buttonsGravity = s.buttonsGravity;
        }

        public Builder title(int titleRes) {
            this.title = ResUtil.getString(context, titleRes);
            return this;
        }

        public Builder titleGravity(GravityEnum gravity) {
            this.titleGravity = gravity;
            return this;
        }

        public Builder titleColor(int color) {
            this.titleColor = ResUtil.getColor(context, color);
            this.titleColorSet = true;
            return this;
        }

        public Builder icon(int iconRes) {
            this.icon = ResUtil.getPixelMapDrawable(context, iconRes);
            return this;
        }

        public Builder content(int contentRes) {
            this.content = ResUtil.getString(context, contentRes);
            return this;
        }

        public Builder contentColor(int color) {
            this.contentColor = ResUtil.getColor(context, color);
            this.contentColorSet = true;
            return this;
        }

        public Builder contentGravity(GravityEnum gravity) {
            this.contentGravity = gravity;
            return this;
        }

        public Builder items(CharSequence... items) {
            if (this.customView != null) {
                throw new IllegalStateException(
                        "You cannot set items()" + " when you're using a custom view.");
            }
            this.items = new ArrayList<>();
            Collections.addAll(this.items, items);
            return this;
        }

        public Builder itemsCallback(ListCallback callback) {
            this.listCallback = callback;
            this.listCallbackSingleChoice = null;
            this.listCallbackMultiChoice = null;
            return this;
        }

        public Builder itemsLongCallback(ListLongCallback callback) {
            this.listLongCallback = callback;
            this.listCallbackSingleChoice = null;
            this.listCallbackMultiChoice = null;
            return this;
        }

        /**
         * Pass anything below 0 (such as -1) for the selected index to leave all options unselected
         * initially. Otherwise pass the index of an item that will be selected initially.
         *
         * @param selectedIndex The checkbox index that will be selected initially.
         * @param callback      The callback that will be called when the presses the positive button.
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder itemsCallbackSingleChoice(int selectedIndex, ListCallbackSingleChoice callback) {
            this.selectedIndex = selectedIndex;
            this.listCallback = null;
            this.listCallbackSingleChoice = callback;
            this.listCallbackMultiChoice = null;
            return this;
        }

        /**
         * Pass null for the selected indices to leave all options unselected initially. Otherwise pass
         * an array of indices that will be selected initially.
         *
         * @param selectedIndices The radio button indices that will be selected initially.
         * @param callback        The callback that will be called when the presses the positive button.
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder itemsCallbackMultiChoice(
                Integer[] selectedIndices, ListCallbackMultiChoice callback) {
            this.selectedIndices = selectedIndices;
            this.listCallback = null;
            this.listCallbackSingleChoice = null;
            this.listCallbackMultiChoice = callback;
            return this;
        }

        /**
         * Sets indices of items that are not clickable. If they are checkboxes or radio buttons, they
         * will not be toggleable.
         *
         * @param disabledIndices The item indices that will be disabled from selection.
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder itemsDisabledIndices(Integer... disabledIndices) {
            this.disabledIndices = disabledIndices;
            return this;
        }

        /**
         * By default, the multi choice callback is only called when the user clicks the positive button
         * or if there are no buttons. Call this to force it to always call on item clicks even if the
         * positive button exists.
         *
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder alwaysCallMultiChoiceCallback() {
            this.alwaysCallMultiChoiceCallback = true;
            return this;
        }

        public Builder positiveText(int positiveRes) {
            if (positiveRes == 0) {
                return this;
            }
            this.positiveText = ResUtil.getString(context, positiveRes);
            return this;
        }

        public Builder positiveColor(int colorStateList) {
            this.positiveColor = ResUtil.getColor(context, colorStateList);
            this.positiveColorSet = true;
            return this;
        }

        public Builder neutralText(int neutralRes) {
            if (neutralRes == 0) {
                return this;
            }
            this.neutralText = ResUtil.getString(context, neutralRes);
            return this;
        }

        public Builder negativeColor(int colorStateList) {
            this.negativeColor = ResUtil.getColor(context, colorStateList);
            this.negativeColorSet = true;
            return this;
        }

        public Builder negativeText(int negativeRes) {
            if (negativeRes == 0) {
                return this;
            }
            this.negativeText = ResUtil.getString(context, negativeRes);
            return this;
        }

        public Builder btnSelector(int selectorRes, DialogAction which) {
            switch (which) {
                default:
                    this.btnSelectorPositive = selectorRes;
                    break;
                case NEUTRAL:
                    this.btnSelectorNeutral = selectorRes;
                    break;
                case NEGATIVE:
                    this.btnSelectorNegative = selectorRes;
                    break;
            }
            return this;
        }

        /**
         * Sets the gravity used for the text in stacked action buttons. By default, it's #{@link
         * GravityEnum#END}.
         *
         * @param gravity The gravity to use.
         * @return The Builder instance so calls can be chained.
         */
        public Builder btnStackedGravity(GravityEnum gravity) {
            this.btnStackedGravity = gravity;
            return this;
        }

        public Builder checkBoxPrompt(
                int prompt, boolean initiallyChecked,
                Checkbox.CheckedStateChangedListener checkListener) {
            this.checkBoxPrompt = ResUtil.getString(context, prompt);
            this.checkBoxPromptInitiallyChecked = initiallyChecked;
            this.checkBoxPromptListener = checkListener;
            return this;
        }

        public Builder customView(int layoutRes, boolean wrapInScrollView) {
            LayoutScatter li = LayoutScatter.getInstance(context);
            return customView(li.parse(layoutRes, null, false), wrapInScrollView);
        }

        Builder customView(Component view, boolean wrapInScrollView) {
            if (this.content != null) {
                throw new IllegalStateException("You cannot use customView() when you have content set.");
            } else if (this.items != null) {
                throw new IllegalStateException("You cannot use customView() when you have items set.");
            } else if (this.inputCallback != null) {
                throw new IllegalStateException("You cannot use customView() with an input dialog");
            } else if (this.progress > -2 || this.indeterminateProgress) {
                throw new IllegalStateException("You cannot use customView() with a progress dialog");
            }
            if (view.getComponentParent() != null && view.getComponentParent() instanceof ComponentContainer) {
                view.getComponentParent().removeComponent(view);
            }
            this.customView = view;
            this.wrapCustomViewInScroll = wrapInScrollView;
            return this;
        }

        /**
         * Makes this dialog a progress dialog.
         *
         * @param indeterminate If true, an infinite circular spinner is shown. If false, a horizontal
         *                      progress bar is shown that is incremented or set via the built MaterialDialog instance.
         * @param max           When indeterminate is false, the max value the horizontal progress bar can get to.
         * @return An instance of the Builder so calls can be chained.
         */
        public Builder progress(boolean indeterminate, int max) {
            if (this.customView != null) {
                throw new IllegalStateException("You cannot set progress() when you're using a custom view.");
            }
            if (indeterminate) {
                this.indeterminateProgress = true;
                this.progress = -2;
            } else {
                this.indeterminateIsHorizontalProgress = false;
                this.indeterminateProgress = false;
                this.progress = -1;
                this.progressMax = max;
            }
            return this;
        }

        /**
         * Makes this dialog a progress dialog.
         *
         * @param indeterminate If true, an infinite circular spinner is shown. If false, a horizontal
         *                      progress bar is shown that is incremented or set via the built MaterialDialog instance.
         * @param max           When indeterminate is false, the max value the horizontal progress bar can get to.
         * @param showMinMax    For determinate dialogs, the min and max will be displayed to the left
         *                      (start) of the progress bar, e.g. 50/100.
         * @return An instance of the Builder so calls can be chained.
         */
        public Builder progress(boolean indeterminate, int max, boolean showMinMax) {
            this.showMinMax = showMinMax;
            return progress(indeterminate, max);
        }

        /**
         * progressIndeterminateStyle
         * <p>
         * By default, indeterminate progress dialogs will use a circular indicator. You can change it
         * to use a horizontal progress indicator.
         *
         * @param horizontal
         * @return builder
         */
        public Builder progressIndeterminateStyle(boolean horizontal) {
            this.indeterminateIsHorizontalProgress = horizontal;
            return this;
        }

        public Builder dividerColor(int color) {
            this.dividerColor = ResUtil.getColor(context, color);
            this.dividerColorSet = true;
            return this;
        }

        public Builder backgroundColor(int color) {
            this.backgroundColor = ResUtil.getColor(context, color);
            return this;
        }

        public Builder onPositive(SingleButtonCallback callback) {
            this.onPositiveCallback = callback;
            return this;
        }

        public Builder onNeutral(SingleButtonCallback callback) {
            this.onNeutralCallback = callback;
            return this;
        }

        public Builder onAny(SingleButtonCallback callback) {
            this.onAnyCallback = callback;
            return this;
        }

        /**
         * This defaults to true. If set to false, the dialog will not automatically be dismissed when
         * an action button is pressed, and not automatically dismissed when the user selects a list
         * item.
         *
         * @param dismiss Whether or not to dismiss the dialog automatically.
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder autoDismiss(boolean dismiss) {
            this.autoDismiss = dismiss;
            return this;
        }

        /**
         * baseItemProvider
         *
         * @param baseItemProvider The baseItemProvider to set to the list.
         * @return This Builder object to allow for chaining of calls to set methods
         */
        public Builder baseItemProvider(BaseItemProvider baseItemProvider) {
            if (this.customView != null) {
                throw new IllegalStateException("You cannot set adapter() when " + "you're using a custom view.");
            }
            this.baseItemProvider = baseItemProvider;
            return this;
        }

        /**
         * limitIconToDefaultSize
         * <p>
         * Limits the display size of a set icon to 48dp.
         *
         * @return builder
         */
        public Builder limitIconToDefaultSize() {
            this.limitIconToDefaultSize = true;
            return this;
        }

        public Builder showListener(OnShowListener listener) {
            this.showListener = listener;
            return this;
        }

        public Builder dismissListener(OnDismissListener listener) {
            this.dismissListener = listener;
            return this;
        }

        public Builder cancelListener(OnCancelListener listener) {
            this.cancelListener = listener;
            return this;
        }

        /**
         * Sets action button stacking behavior.
         *
         * @param behavior The behavior of the action button stacking logic.
         * @return The Builder instance so you can chain calls to it.
         */
        public Builder stackingBehavior(StackingBehavior behavior) {
            this.stackingBehavior = behavior;
            return this;
        }

        Builder input(
                CharSequence hint,
                CharSequence prefill, boolean allowEmptyInput,
                InputCallback callback) {
            if (this.customView != null) {
                throw new IllegalStateException("You cannot set content() when " + "you're using a custom view.");
            }
            this.inputCallback = callback;
            this.inputHint = hint;
            this.inputPrefill = prefill;
            this.inputAllowEmpty = allowEmptyInput;
            return this;
        }

        public Builder input(
                int hint,
                int prefill, boolean allowEmptyInput,
                InputCallback callback) {
            return input(hint == 0 ? null : ResUtil.getString(context, hint),
                    prefill == 0 ? null : ResUtil.getString(context, prefill), allowEmptyInput, callback);
        }

        public Builder inputType(int type) {
            this.inputType = type;
            return this;
        }

        public Builder inputRange(int minLength, int maxLength) {
            return inputRange(minLength, maxLength, 0);
        }

        /**
         * inputRange
         *
         * @param maxLength
         * @param minLength
         * @param errorColor Pass in 0 for the default red error color (as specified in guidelines).
         * @return builder
         */
        Builder inputRange(
                int minLength,
                int maxLength,
                int errorColor) {
            if (minLength < 0) {
                throw new IllegalArgumentException("Min length for input dialogs " + "cannot be less than 0.");
            }
            this.inputMinLength = minLength;
            this.inputMaxLength = maxLength;
            if (errorColor == 0) {
                this.inputRangeErrorColor = ResUtil.getColor(context, ResourceTable.Color_md_edittext_error);
            } else {
                this.inputRangeErrorColor = errorColor;
            }
            if (this.inputMinLength > 0) {
                this.inputAllowEmpty = false;
            }
            return this;
        }

        public Builder alwaysCallInputCallback() {
            this.alwaysCallInputCallback = true;
            return this;
        }

        public Builder tag(Object tag) {
            this.tag = tag;
            return this;
        }


        public MaterialDialog build() {
            return new MaterialDialog(this);
        }


        public MaterialDialog show() {
            MaterialDialog dialog = build();
            dialog.show();
            return dialog;
        }
    }

    /**
     * Override these as needed, so no needing to sub empty methods from an interface
     *
     * @deprecated Use the individual onPositive, onNegative, onNeutral, or onAny Builder methods
     * instead.
     */
    public abstract static class ButtonCallback {

        public ButtonCallback() {
            super();
        }

        void onAny(MaterialDialog dialog) {
        }

        void onPositive(MaterialDialog dialog) {
        }

        void onNegative(MaterialDialog dialog) {
        }

        // The overidden methods below prevent suggesting that they are overidden by developers
        void onNeutral(MaterialDialog dialog) {
        }

        @Override
        protected final Object clone() throws CloneNotSupportedException {
            return super.clone();
        }

        @Override
        public final boolean equals(Object o) {
            return super.equals(o);
        }

        @Override
        protected final void finalize() throws Throwable {
            super.finalize();
        }

        @Override
        public final int hashCode() {
            return super.hashCode();
        }

        @Override
        public final String toString() {
            return super.toString();
        }
    }
}
